'use strict';
const db = uniCloud.database()
const accountCollection = db.collection("Accounts")

exports.main = async (event, context) => {
	try {
		const {
			loginVal,
			password
		} = event;
		console.log("[云函数 login]登录请求：", {
			loginVal,
			password: "******"
		});
		const res = await accountCollection.where({
			$or: [{
					name: loginVal
				},
				{
					phone: loginVal
				}
			],
			password: password
		}).get();

		if (res.data.length > 0) {
			const userInfo = res.data[0];
			userInfo.password = "******";
			console.log("[云函数 login]登录成功：", userInfo);
			return {
				code: 200,
				msg: "登录成功",
				data: userInfo
			};
		} else {
			console.log("[云函数 login]登录失败：账号/手机号或密码错误");
			return {
				code: 401,
				msg: "账号/手机号或密码错误"
			};
		}
	} catch (err) {
		console.error("[云函数 login]登录异常：", err);
		return {
			code: 500,
			msg: "登录失败：" + err.message
		};
	}
};